package com.xueyi.workflow.listener;

import com.xueyi.workflow.event.ProcessStatusChangedEvent;
import com.xueyi.workflow.service.IWfProcessInstanceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 流程状态变更事件监听器
 * 监听所有流程状态变化事件，并同步更新业务表
 *
 * @author xueyi
 * @date 2024-08-26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ProcessStatusChangedEventListener {
    
    private final IWfProcessInstanceService wfProcessInstanceService;
    
    /**
     * 监听流程状态变更事件
     */
    @EventListener
    @Async
    public void handleProcessStatusChanged(ProcessStatusChangedEvent event) {
        try {
            String processInstanceId = event.getProcessInstanceId();
            String oldStatus = event.getOldStatus();
            String newStatus = event.getNewStatus();
            String reason = event.getReason();
            
            log.info("收到流程状态变更事件，processInstanceId: {}, 状态: {} -> {}, 原因: {}", 
                    processInstanceId, oldStatus, newStatus, reason);
            
            // 根据新状态调用相应的更新方法
            boolean success = false;
            
            switch (newStatus) {
                case "COMPLETED":
                    success = wfProcessInstanceService.updateStatusToCompleted(processInstanceId);
                    break;
                case "SUSPENDED":
                    success = wfProcessInstanceService.updateStatusToSuspended(processInstanceId, reason);
                    break;
                case "RUNNING":
                    success = wfProcessInstanceService.updateStatusToRunning(processInstanceId);
                    break;
                case "TERMINATED":
                    success = wfProcessInstanceService.updateStatusToTerminated(processInstanceId, reason);
                    break;
                case "ERROR":
                    success = wfProcessInstanceService.updateStatusToError(processInstanceId, reason);
                    break;
                default:
                    log.warn("未知的流程状态: {}, processInstanceId: {}", newStatus, processInstanceId);
                    success = false;
            }
            
            if (success) {
                log.info("流程实例 {} 状态更新成功，新状态: {}", processInstanceId, newStatus);
            } else {
                log.warn("流程实例 {} 状态更新失败，新状态: {}", processInstanceId, newStatus);
            }
            
        } catch (Exception e) {
            log.error("处理流程状态变更事件失败", e);
        }
    }
}
